<?php

namespace app\api\controller;
use app\common\model\GiftRecord;
use app\common\model\Gift as model;
use app\common\model\MyPackage;
use app\common\model\UserFollow;
use app\common\model\Users;
use Carbon\Carbon;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;
use think\Validate;

class Gift extends  User
{
    /**
     * 礼物列表
     * @param Request $request
     */
    public function  giftList(Request $request)
    {
        $type = $request->param('type');
        
        $model = new model();

        $map['status'] = 1;
        $map['type'] = $type;
        $map['is_special'] = 0;
        $rows['gift'] = $model->giftList($map);
        $rows['coin'] = $this->userInfo('coin');
        $rows['money'] = $this->userInfo('money');

        api_return(1,'获取成功',$rows);
    }

    /**
     * 我的背包礼物列表
     * @param Request $request
     */
    public function myPackage(Request $request)
    {
        $map['user_id'] = $this->user_id;
        $map['p.type']  = 1;
        $map['num']     = ['>',0];
        $rows['gift']   = MyPackage::getRows($map);

        $map['p.type']  = 2;
        $rows['card']   = MyPackage::getCard($map);

        $rows['coin']   = $this->userInfo('coin');
        $rows['money']  = $this->userInfo('money');

        api_return(1,'获取成功',$rows);
    }

    /**
     * 购买礼物
     * @param Request $request
     */
    public function buyGift(Request $request)
    {
        $request = $request->only(['gift_id','num']);

        $validate = new Validate([
            'gift_id' => 'require|number',
            'num' => 'require|number',
        ]);
        if (!$validate->check($request)) {
            get_error_msg($validate->getError());
        }

        $gift = model::get($request['gift_id']);
        if(!$gift)api_return(0,'没有该商品');
        $total = bcmul($gift['price'],$request['num']);
        Db::startTrans();
        try{
            if($gift['type'] == 2)
            {
                $this->accountDec($total,'coin');
                $type = 3;
            }else{
                $this->accountDec($total);
                $type = 1;
            }
            money_detail(2,$this->user_id, '('.$gift['gift_name'].')礼物购买',$total,'消费',$type);

            $data['user_id'] = $this->user_id;
            $data['num'] = $request['num'];
            $data['key'] = $request['gift_id'];
            MyPackage::create($data);
            Db::commit();
        }catch(Exception $e){
            Db::rollback();
            Log::error($e->getMessage());
            api_return(0,'购买失败');
        }
        api_return(1,'购买成功');
    }

    /**
     * 我的资产 -> 礼物 统计列表
     */
    public function myList()
    {
        $where['a.to_user'] = $this->user_id;
        $map['a.user_id']   = $this->user_id;
        $model = new GiftRecord();
        $rows['get']  = $model->giftCount($where);
        $rows['send'] = $model->giftCount($map);
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 收益 => 礼物列表
     */
    public function myGiftList()
    {
        $model = new GiftRecord();

        $map['a.status'] = 1;
        $map['a.to_user'] = $this->user_id;

        $rows = $model->_list($map);
        $rows['total'] = (string) $model->alias('a')->sum('total');
        api_return(1,'获取成功',$rows);

    }
    
    /**
     * 我收到|发出的礼物详情
     */
    public function giftDetail()
    {
        $where = [];
        if (is_numeric(input('post.id'))){
            $where['a.gift_id'] = input('post.id');
        }
        if (!empty(input('post.time'))){
            $time = input('post.time');
            $info = date_parse_from_format('Y-m',$time);
            if ( 0 != $info['warning_count'] || 0 != $info['error_count']) api_return(0,'时间错误');
            $start = strtotime($time);
            $end   = strtotime($time.'-'.date('t', strtotime($start)).' 23:59:59');
            $where['a.create_time'] = ['between time',[$start,$end]];
        }
        $type = input('post.type');
        if ($type == 1){ //我收到的
            $where['a.to_user'] = $this->user_id;
        }elseif ($type == 2){ //我送出的礼物
            $where['a.user_id'] = $this->user_id;
        }else{
            api_return(0,'参数错误');
        }
        $model = new GiftRecord();
        $rows  = $model->myDetail($where,$type);
        $rows['total'] = $model->alias('a')->where($where)->sum('total');
        if ($rows !== false) api_return(1,'获取成功',$rows);
        api_return(0,'暂无数据');

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 余额赠送礼物
     */
    public function giftGiving()
    {

        $data  = input('post.');
        $array = $this->giveGift($data,$this->user_id);
        $price = $array['price'];
        //查询背包数量
        $map['user_id'] = $this->user_id;
        $map['type']    = 1;
        $map['key']     = $array['id'];
        $num = Db::name('my_package')->where($map)->value('num')??0;

        Db::startTrans();
        try{

            //背包内还剩余礼物
            if ($num != 0){

                //背包足够赠送礼物
                if ($num >= $array['allNum']){
                    Db::name('my_package')->where($map)->setDec('num',$array['allNum']);
                }else{
                    //背包不够赠送礼物
                    Db::name('my_package')->where($map)->setDec('num',$num);
                    $number = $array['allNum'] - $num;

                    $money  = bcmul($number,$array['onePrice'],2);

                    switch ($array['gift_type']){
                        case 1://钻石礼物
                            $this->moneyDec($money,$this->user_id);
                            break;
                        case 2://金币礼物
                            $coin = Users::where('user_id',$this->user_id)->value('coin');
                            if ($coin < $money){
                                api_return(0,'金币不足');
                            }
                            Db::name('users')->where('user_id',$this->user_id)->setDec('coin',$money);
                            break;
                        default:
                            api_return(0,'礼物类型错误');
                    }
                }

            }else{
                switch ($array['gift_type']){
                    case 1://钻石礼物
                        $this->moneyDec($price,$this->user_id);
                        break;
                    case 2://金币礼物
                        $coin = Users::where('user_id',$this->user_id)->value('coin');
                        if ($coin < $price){
                            api_return(0,'金币不足');
                        }
                        Db::name('users')->where('user_id',$this->user_id)->setDec('coin',$price);
                        break;
                    default:
                        api_return(0,'礼物类型错误');
                }
            }

            $this->gift($array,$this->user_id);
            $this->addLevel($array['price'],$this->user_id);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,'系统错误',$e->getMessage());
        }

        api_return(1,'赠送成功');
    }

    /**
     * 魅力榜、财富榜
     * status 1 魅力榜   2 财富榜
     */
    public function rankingList(Request $request)
    {
        $request = $request->only(['status','type','room_id']);

        switch ($request['type'])
        {
            case 1: //今日
                $stat_time =  Carbon::today()->timestamp;
                break;
            case 2: //本周
                $stat_time = Carbon::now()->startOfWeek()->timestamp;
                break;
            default: //总榜
                $stat_time = 0;
                break;
        }
        $end_time = time();
        $map['a.status'] = 1;
        //$map['a.room_id'] = ['>',0];
        $map['a.create_time'] = ['between time', [$stat_time, $end_time]];

        if (isInt($request['room_id'])){
            $map['a.room_id'] = $request['room_id'];
        }

        $model = new GiftRecord();
        if($request['status'] ==1)
        {
            $rows = $model->ranking($map);
        }else{
            $rows = $model->ranking($map,'user_id');
        }

        api_return(1,'获取成功',$rows);
    }


    /**
     * 周星礼物列表
     */
    public function weekGifts()
    {
        $gifts = model::where('is_naming',1)->field('gift_id,gift_name,thumbnail')->select();
        api_return(1,'获取成功',$gifts);
    }


    /**
     * 周星榜
     */
    public function WeekList(Request $request)
    {
        $request = $request->only(['gift_id','type']);
        
        $map['a.status'] = 1;
        //$map['a.room_id'] = ['>',0];
        $request['gift_id'] && $map['a.gift_id'] = $request['gift_id'];
        $stat_time = Carbon::now()->startOfWeek()->timestamp;
        $map['a.create_time'] = ['between time', [$stat_time, time()]];
        
        $model = new GiftRecord();
        if($request['type'] ==1)
        {
            $rows = $model->weekList($map);
        }else{
            $rows = $model->weekList($map,'user_id');
        }

        api_return(1,'获取成功',$rows);
    }


    //------------------排行榜----------

    /**
     * 明星榜
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function starList(Request $request)
    {
        $status = $request->param('status');

        $map = [];
        if($status ==2)
        {
            $stat_time = Carbon::now()->startOfWeek()->timestamp;
            $map['a.create_time'] = ['between time', [$stat_time, time()]];
        }

        $rows = GiftRecord::starList($map);
        api_return(1,'获取成功',$rows);
    }

    /**
     * 富豪榜
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function richList(Request $request)
    {
        $status = $request->param('status');

        $map = [];
        if($status ==2)
        {
            $stat_time = Carbon::now()->startOfWeek()->timestamp;
            $map['a.create_time'] = ['between time', [$stat_time, time()]];
        }

        $rows = GiftRecord::richList($map,'user_id');

        api_return(1,'获取成功',$rows);
    }

    /**
     * 人气榜
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function popularityList(Request $request)
    {
        $status = $request->param('status');

        $map = [];
        if($status ==2)
        {
            $stat_time = Carbon::now()->startOfWeek()->timestamp;
            $map['a.create_time'] = ['between time', [$stat_time, time()]];
        }

        $rows = UserFollow::popularityList($map,'follow_user');

        api_return(1,'获取成功',$rows);
    }

}